package com.hongdee.scm.inventory.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.inventory.dao.ITScmInventoryDetailDao;
import com.hongdee.scm.inventory.entity.TScmInventoryDetail;
import com.hongdee.scm.inventory.service.ITScmInventoryDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 名  称:TScmInventoryDetailServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.scm.inventory.service.impl
 * 作  者: 术洪超
 * 日  期:2017-06-01 15:35
 */
@Service
public class TScmInventoryDetailServiceImpl implements ITScmInventoryDetailService {


    String tabName = "T_SCM_INVENTORY_DETAIL";
    String entityName = "TScmInventoryDetail";

    @Autowired
    private ITScmInventoryDetailDao itScmInventoryDetailDao;

    @Override
    public Map info(String id) throws Exception {
        List param = new ArrayList();
        String sql = "select * from " + tabName + " where id = ?";
        param.add(id);
        return this.itScmInventoryDetailDao.info(sql, param.toArray());
    }

    /**
     * 发票明细保存
     *
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void saveOrUpdateDetail(List<Map> data, String uid, String id) throws Exception {
        if (data.size() > 0) {
            for (Map map : data) {
                TScmInventoryDetail entity = new TScmInventoryDetail();
                if (map.get("vin") != null && !map.get("vin").equals("")) {
                    entity.setVin(map.get("vin").toString());
                }
                entity.setCreateUser(uid);
                entity.setInventoryId(id);
                entity.setCreateTime(Calendar.getInstance().getTimeInMillis());
                entity.setCompanyId(TokenUtil.getCompanyId(uid));
                if (map.get("carModel") != null && !map.get("carModel").equals("")) {
                    entity.setCarModel(map.get("carModel").toString());
                }
                if (map.get("configureName") != null && !map.get("configureName").equals("")) {
                    entity.setConfigureName(map.get("configureName").toString());
                }
                this.itScmInventoryDetailDao.saveOrUpdate(entity);
            }
        } else {
            throw new Exception("请选择车辆！");
        }

    }


    @Override
    public void update(String id) throws Exception {

    }

    @Override
    public Map page(String start, String limit, String vin, String carModel, String id, String uid) throws Exception {

        List params = new ArrayList();
        String sql = "select * from " + tabName + " where inventory_id = ? and company_id = ?";

        params.add(id);
        params.add(TokenUtil.getCompanyId(uid));

        if (vin != null && !StringUtils.isEmpty(vin)) {
            sql += " and vin like ?";
            params.add(vin);
        }

        if (carModel != null && !StringUtils.isEmpty(carModel)) {
            sql += " and carModel = ?";
            params.add(carModel);
        }
        sql += " order by difference_type,result_reason ";
        return this.itScmInventoryDetailDao.page(sql, params.toArray(), start, limit);
    }


    @Override
    public void updateValidateStatus(String[] vins,String uid,String inventoryId) throws Exception {

        //判断该月的月结是否结束
        String taskName = this.itScmInventoryDetailDao.info("select * from t_scm_inventory where id=?",inventoryId).get("taskName").toString();
        Boolean flag = true;
        String str = "";
        try{
            str = taskName.substring(0,6);
        }catch (Exception e){
            flag = false;
        }
        if(flag){
            if(this.itScmInventoryDetailDao.info("select * from t_scm_monthlybalance where monthly_balance_month = ? and monthly_balance_status = '0' ",str).size()>0){
                throw new Exception("月结结束,不能再盘点车辆!");
            }
        }

        for (String vin:vins) {

           List<Map<String,Object>> list = this.itScmInventoryDetailDao.list("select c.car_model,c.configure,s.difference_type,s.company_id from t_scm_stock s left join t_scm_car c on s.car_id = c.id where s.vin = ? and s.company_id=?",vin,TokenUtil.getCompanyId(uid));
           if(this.itScmInventoryDetailDao.list("select * from t_scm_inventory_detail where vin =? and inventory_status='1' and company_id=?",vin,TokenUtil.getCompanyId(uid)).size()>0){
                throw new Exception(vin+"已打印");
           }
           String sql = "select * from t_scm_inventory_detail where vin =? and inventory_id = ?";
           List params = new ArrayList();
           params.add(vin);
           params.add(inventoryId);
           if(this.itScmInventoryDetailDao.info(sql,params.toArray()).size()>0){
               this.itScmInventoryDetailDao.executeSQL("update t_scm_inventory_detail set inventory_status = '1' where vin = ? and inventory_id =? and company_id=?",vin,inventoryId,TokenUtil.getCompanyId(uid));
           }else{
               TScmInventoryDetail entity = new TScmInventoryDetail();
               entity.setCarModel(list.get(0).get("carModel").toString());
               entity.setConfigureName(list.get(0).get("configure").toString());
               entity.setCompanyId(list.get(0).get("companyId").toString());
               entity.setInventoryId(inventoryId);
               entity.setVin(vin);
               entity.setInventoryStatus("1");
               entity.setCreateTime(Calendar.getInstance().getTimeInMillis());
               entity.setCreateUser(uid);

               this.itScmInventoryDetailDao.saveOrUpdate(entity);
           }
        }
       /* StringBuffer hql = new StringBuffer();
        hql.append("update " + tabName + " set inventory_status = '1' ");
        List params = new ArrayList();
        if (vins.length > 0) {
            hql.append(" where vin in ( ");
            for (Object vin : vins) {
                hql.append(" ? , ");
                params.add(vin);
            }
            hql.append(" '' ) ");
        }
        this.itScmInventoryDetailDao.executeSQL(hql.toString(), params.toArray());*/
    }

    /**
     * 盘点的车辆数/自动处理盘点结果
     * @param uid
     * @param id
     * @throws Exception
     */
    @Override
    public void countInventoryCar(String uid,String id) throws Exception{

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        Map param = new HashMap();
        StringBuffer hqls = new StringBuffer();
        StringBuffer resultReason = new StringBuffer();
        //盘点的车辆数
        sql.append("select count(1) as value from t_scm_inventory_detail where inventory_id =? ");
        params.add(id);
        sql.append("group by inventory_id");
        Map map = this.itScmInventoryDetailDao.info(sql.toString(),params.toArray());
        this.itScmInventoryDetailDao.executeSQL("update t_scm_inventory set car_count=? where id = ? ",map.get("value"),id);

        //自动处理盘点结果
        if(this.itScmInventoryDetailDao.list("select * from t_scm_inventory_detail where inventory_id =? and (difference_type is null or difference_type ='') ",id).size()<=0){
            List<Map<String,Object>> list= this.itScmInventoryDetailDao.list("select difference_type type ,count(1) as value from t_scm_inventory_detail " +
                    "where inventory_id = ? GROUP BY difference_type",id);
            for(Map<String,Object> m:list){
                resultReason.append(m.get("type")+":"+m.get("value").toString()+" ");
            }
            hqls.append("update TScmInventory set result=:result,inventoryDate=:inventoryDate,resultReason=:resultReason" +
                    " where id=:inventoryId ");
            param.put("result","盘点结束");
            param.put("inventoryDate",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            param.put("resultReason",resultReason.toString());
            param.put("inventoryId",id);
            this.itScmInventoryDetailDao.update(hqls.toString(), param);
        }
    }

}
